package com.sxx.mall.member.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxx.commons.utils.HttpUtils;
import com.sxx.commons.utils.PageUtils;
import com.sxx.commons.utils.Query;
import com.sxx.mall.member.dao.MemberDao;
import com.sxx.mall.member.entity.MemberEntity;
import com.sxx.mall.member.entity.MemberLevelEntity;
import com.sxx.mall.member.exception.PhoneExsitException;
import com.sxx.mall.member.exception.UsernameExsitException;
import com.sxx.mall.member.service.MemberLevelService;
import com.sxx.mall.member.service.MemberService;
import com.sxx.mall.member.vo.MemberLoginVO;
import com.sxx.mall.member.vo.MemberRegisterVO;
import com.sxx.mall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelService memberLevelService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVO vo) throws PhoneExsitException,UsernameExsitException {
        MemberEntity memberEntity = new MemberEntity();
        //设置会员等级 默认值
        MemberLevelEntity memberLevelEntity = memberLevelService.queryMemberLeveldefault();
        memberEntity.setLevelId(memberLevelEntity.getId());//设置默认会员等级
        //添加对应的账号和手机号是不能重复的
        checkUsernameUnique(vo.getUserName());
        checkPhoneUnique(vo.getPhone());

        memberEntity.setUsername(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setNickname(vo.getUserName());//默认昵称为用户名：账号
        //需要对密码做加密处理
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);

        this.save(memberEntity);
    }

    @Override
    public MemberEntity login(MemberLoginVO vo) {
        // 1.根据账号或者手机号来查询会员信息
        MemberEntity entity = this.getOne(new QueryWrapper<MemberEntity>()
                .eq("username", vo.getUserName())
                .or()
                .eq("mobile", vo.getUserName()));
        if(entity != null){
            // 2.如果账号或者手机号存在 然后根据密码加密后的校验来判断是否登录成功
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(vo.getPassword(), entity.getPassword());
            if(matches){
                // 表明登录成功
                return entity;
            }
        }
        return null;
    }

    /**
     * 社交登录
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(SocialUser vo) {
        String uid = vo.getUid();
        //1.if如果不是第一次社交登录，那么就更新相关信息 登录功能
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null){
            //说明当前用户已经注册过了, 更新token和过期时间
            MemberEntity entity = new MemberEntity();
            entity.setId(memberEntity.getId());
            entity.setAccessTocken(vo.getAccessToken());
            entity.setExpiresIn(vo.getExpiresIn());
            this.updateById(entity);
            //在返回的登录用户信息中我们同步的也保存token 和过期时间
            memberEntity.setAccessTocken(vo.getAccessToken());
            memberEntity.setExpiresIn(vo.getExpiresIn());
            return memberEntity;
        }
        //2.else表示用户是第一次提交，需要根据vo对象来注册
        MemberEntity mEntity = new MemberEntity();
        mEntity.setAccessTocken(vo.getAccessToken());
        mEntity.setExpiresIn(vo.getExpiresIn());
        mEntity.setSocialUid(vo.getUid());
        //通过tocken调用微博开放的接口获取用户信息
        try{
            Map<String, String> querys = new HashMap<>();
            querys.put("access_token",vo.getAccessToken());
            querys.put("uid",vo.getUid());
            HttpResponse response = HttpUtils
                    .doGet("https://api.weibo.com",
                    "/2/users/show.json",
                    "get",
                    new HashMap<>(),
                    querys
            );
            if (response.getStatusLine().getStatusCode() == 200){
                String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                String nickName = jsonObject.getString("screen_name");
                String headImg = jsonObject.getString("profile_image_url");
                String gender = jsonObject.getString("gender");
                mEntity.setNickname(nickName);
                mEntity.setHeader(headImg);
                mEntity.setGender("m".equals(gender)?1:0);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //注册用户信息
        this.save(mEntity);
        return mEntity;
    }

    /*
    * 校验手机号是否存在
    * */
    private void checkPhoneUnique(String phone) throws PhoneExsitException {
        long mobile = this.count(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0){
            //说明手机号存在
            throw new PhoneExsitException();
        }
    }

    /*
    * 校验账号是否存在
    * */
    private void checkUsernameUnique(String userName) throws UsernameExsitException {
        long username = this.count(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (username > 0){
            //说明账号存在
            throw new UsernameExsitException();
        }
    }

}